﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CK.Sprite.CrossCutting
{
    /// <summary>
    /// 雪花算法生成Id
    /// </summary>
    public class SnowflakeId
    {
        private static ConcurrentDictionary<string, SnowflakeId> SnowflakeIdDict;

        static SnowflakeId()
        {
            SnowflakeIdDict = new ConcurrentDictionary<string, SnowflakeId>();
            var spriteConfig = (IOptions<SpriteConfig>)ServiceLocator.ServiceProvider.GetService(typeof(IOptions<SpriteConfig>));
            workerId = spriteConfig.Value.SnowflakeWorkerId;
        }

        #region 静态字段值

        /// <summary>
        /// 机器ID
        /// </summary>
        private static long workerId;
        /// <summary>
        /// 唯一时间，这是一个避免重复的随机量，自行设定不要大于当前时间戳
        /// </summary>
        private static long twepoch = 687888001020L;
        private static long sequence = 0L;
        /// <summary>
        /// /机器码字节数。4个字节用来保存机器码(定义为Long类型会出现，最大偏移64位，所以左移64位没有意义)
        /// </summary>
        private static int workerIdBits = 4;
        /// <summary>
        /// 最大机器ID
        /// </summary>
        public static long maxWorkerId = -1L ^ -1L << workerIdBits;
        /// <summary>
        /// 计数器字节数，10个字节用来保存计数码
        /// </summary>
        private static int sequenceBits = 10;
        /// <summary>
        /// 机器码数据左移位数，就是后面计数器占用的位数
        /// </summary>
        private static int workerIdShift = sequenceBits;
        /// <summary>
        /// 时间戳左移动位数就是机器码和计数器总字节数
        /// </summary>
        private static int timestampLeftShift = sequenceBits + workerIdBits;
        /// <summary>
        /// 一微秒内可以产生计数，如果达到该值则等到下一微妙在进行生成
        /// </summary>
        public static long sequenceMask = -1L ^ -1L << sequenceBits;
        private static long lastTimestamp = -1L;

        #endregion

        private object objLock = new object();

        /// <summary>
        /// 生成Id，
        /// </summary>
        /// <param name="strKey">对象标识，每一个标识维护自己的算法</param>
        public static string GetSnowflakeId(string strKey, string preNo = "")
        {
            var snowflakeId = SnowflakeIdDict.GetOrAdd(strKey, new SnowflakeId());
            if(string.IsNullOrEmpty(preNo))
            {
                return snowflakeId.nextId().ToString();
            }
            else
            {
                return $"{preNo}{snowflakeId.nextId().ToString()}";

            }
        }

        /// <summary>
        /// 获取Id
        /// </summary>
        /// <returns></returns>
        public long nextId()
        {
            lock (objLock)
            {
                long timestamp = timeGen();
                if (lastTimestamp == timestamp)
                { 
                    //同一微秒中生成ID
                    SnowflakeId.sequence = (SnowflakeId.sequence + 1) & SnowflakeId.sequenceMask; 
                    //用&运算计算该微秒内产生的计数是否已经到达上限
                    if (SnowflakeId.sequence == 0)
                    {
                        //一微妙内产生的ID计数已达上限，等待下一微妙
                        timestamp = tillNextMillis(lastTimestamp);
                    }
                }
                else
                {
                    //不同微秒生成ID
                    //计数清0
                    SnowflakeId.sequence = 0; 
                }
                if (timestamp < lastTimestamp)
                { 
                    //如果当前时间戳比上一次生成ID时时间戳还小，抛出异常，因为不能保证现在生成的ID之前没有生成过
                    throw new Exception(string.Format("Clock moved backwards.  Refusing to generate id for {0} milliseconds",
                        lastTimestamp - timestamp));
                }
                //把当前时间戳保存为最后生成ID的时间戳
                lastTimestamp = timestamp;
                long nextId = (timestamp - twepoch << timestampLeftShift) | SnowflakeId.workerId << SnowflakeId.workerIdShift | SnowflakeId.sequence;
                return nextId;
            }
        }

        /// <summary>
        /// 获取下一微秒时间戳
        /// </summary>
        /// <param name="lastTimestamp"></param>
        /// <returns></returns>
        private long tillNextMillis(long lastTimestamp)
        {
            long timestamp = timeGen();
            while (timestamp <= lastTimestamp)
            {
                timestamp = timeGen();
            }
            return timestamp;
        }

        /// <summary>
        /// 生成当前时间戳
        /// </summary>
        /// <returns></returns>
        private long timeGen()
        {
            return (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }
    }
}
